<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <div class="cate">
        选择商品分类：
        <el-cascader
          v-model="selectedVal"
          :options="cateList"
          :props="cateProps"
          @change="cateChange"
        ></el-cascader>
      </div>
      <template>
        <el-tabs v-model="activeName" @tab-click="tabsClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="open" type="primary" size="mini" round :disabled="isDisabled">添加参数</el-button>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="open" type="primary" size="mini" round :disabled="isDisabled">添加属性</el-button>
          </el-tab-pane>
        </el-tabs>
      </template>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染的tag -->
            <el-tag
              closable
              @close="tagDelete(scope.row,index)"
              v-for="(item,index) in scope.row.attr_vals"
              :key="index"
            >{{item}}</el-tag>
            <!-- 添加的tag -->
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            ></el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(scope.row)"
            >+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              round
              class="r_m_btns"
              @click="editParams(scope.row)"
            >编辑</el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              round
              class="r_m_btns"
              @click="deleteParams(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog @close="dialogClose" title="提示" :visible.sync="addDatadialogVisible" width="30%">
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="changeLabel" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDatadialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAddData()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      @close="editDialogClose"
      title="提示"
      :visible.sync="editDatadialogVisible"
      width="30%"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="changeLabel" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDatadialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subEditData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      selectedVal: [],
      cateProps: { expandTrigger: "hover", label: "cat_name", value: "cat_id" },
      activeName: "many",
      // 动态参数
      manyData: [],
      // 静态属性
      onlyData: [],
      addDatadialogVisible: false,
      addParamsForm: {
        attr_name: ""
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      },
      editDatadialogVisible: false,
      editParamsForm: {},
      editParamsFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      },
      inputVisible: false,
      inputValue: ""
    };
  },

  created() {
    this.getCateList();
  },

  methods: {
    //   获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取分类数据失败");
      this.cateList = res.data;
    },
    async getData() {
      if (this.selectedVal.length !== 3) {
        this.selectedVal = [];
        this.onlyData = [];
        this.manyData = [];
        return;
      }
      console.log(this.selectedVal);
      //获取请求获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("获取参数列表失败");
      console.log(res);
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //为每行添加单独的inputVisible
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") return (this.manyData = res.data);
      this.onlyData = res.data;
    },
    // 级联选择器选择的数据变化时触发
    cateChange() {
      this.getData();
    },
    tabsClick() {
      this.getData();
    },
    deleteParams(row) {
      console.log(row);
    },
    open() {
      this.addDatadialogVisible = true;
    },
    // 添加数据
    subAddData() {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        this.addDatadialogVisible = false;
        this.getData();
      });
    },
    dialogClose() {
      this.$refs.addParamsFormRef.resetFields();
    },
    // 打开编辑参数对话框
    async editParams(row) {
      const { data: res } = await this.$http.get(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("加载失败");
      this.editParamsForm = res.data;
      this.editDatadialogVisible = true;
    },
    // 提交编辑参数
    subEditData() {
      this.$refs.editParamsFormRef.validate(async flag => {
        if (!flag) return;
        const { data: res } = await this.$http.put(
          `categories/${this.editParamsForm.cat_id}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) return this.$message.error("编辑失败");
        this.$message.success("编辑成功");
        this.editDatadialogVisible = false;
        this.getData();
      });
    },
    editDialogClose() {
      this.$refs.editParamsFormRef.resetFields();
    },
    // 删除参数
    deleteParams(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${row.attr_id}`
          );
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getData();
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },
    // 添加tag输入确认
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue);
      this.saveAttr_vals(row);
      row.inputValue = "";
      row.inputVisible = false;
    },
    // 点击new tag按钮
    showInput(row) {
      row.inputVisible = true;
      // 自动获得焦点
      // $nextTick作用是在页面被重新渲染之后才会调用回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async saveAttr_vals(row, index) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("tag修改失败");
      this.$message.success("tag修改成功");
    },
    // 删除tag
    tagDelete(row, index) {
      row.attr_vals.splice(index, 1);
      console.log(row.attr_vals);
      this.saveAttr_vals(row, index);
    }
  },
  computed: {
    cateId() {
      if (this.selectedVal.length == 3) {
        return this.selectedVal[2];
      }
      return null;
    },
    //控制按钮是否禁用
    isDisabled() {
      return this.selectedVal.length !== 3;
    },
    tableData() {
      if (this.activeName == "many") return this.manyData;
      return this.onlyData;
    },
    changeLabel() {
      if (this.activeName == "many") return "动态属性";
      return "静态参数";
    }
  }
};
</script>

<style scoped lang='less'>
.el-breadcrumb {
  margin-bottom: 20px;
  padding: 15px;
}
.cate {
  margin: 20px 0;
}
.el-tag {
  margin: 0 5px;
}
.input-new-tag {
  width: 100px;
}
</style>
